package com.example.springboot4.system.config;

import com.example.springboot4.system.security.handle.LogoutSuccessHandlerImpl;
import com.example.springboot4.system.security.interceptor.RestAuthenticationEntryPoint;
import com.example.springboot4.system.security.interceptor.RestfulAccessDeniedHandler;
import com.example.springboot4.system.security.jwt.JwtAuthenticationTokenFilter;
import com.example.springboot4.system.security.jwt.UserDetailsServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * security配置类
 *
 * @author 宋义州
 * @since 2024/5/11 下午12:39
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    /**
     * 认证失败处理类
     */
    @Resource
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    /**
     * 接口无权限处理
     */
    @Resource
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    /**
     * 退出处理类
     */
    @Resource
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * 跨域过滤器
     */
    @Resource
    private CorsFilter corsFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        // 由于使用的是JWT，我们这里不需要csrf,跨域漏洞防御
        httpSecurity.csrf(AbstractHttpConfigurer::disable);

        // 禁用缓存控制 禁用HTTP响应标头,防止点击劫持攻击
        httpSecurity.headers(headersCustomizer -> headersCustomizer
                .cacheControl(HeadersConfigurer.CacheControlConfig::disable)
                .frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin));

        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling(exceptionHandling -> exceptionHandling
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint));

        // 使用token，关闭session
        httpSecurity.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        httpSecurity.authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
                // 跨域预检请求
                .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // login,wabSocket
                .requestMatchers("/api/system/login").permitAll()
                .requestMatchers("/v3/api-docs/**", "/doc.html", "/swagger-ui/**", "/swagger-resources/**", "/webjars/**").permitAll()
                // 所有其他请求都需要身份验证
                .anyRequest().authenticated());

        // 禁用默认登陆表单
        httpSecurity.formLogin(formLogin -> formLogin
                        .loginPage("/login").permitAll())
                .rememberMe(AbstractHttpConfigurer::disable);

        //管理userDetailsService
        httpSecurity.userDetailsService(userDetailsService);

        // 添加Logout filter
        httpSecurity.logout(logout -> logout.logoutUrl("/api/system/logout").logoutSuccessHandler(logoutSuccessHandler));
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, jwtAuthenticationTokenFilter.getClass());
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);

        return httpSecurity.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 获取AuthenticationManager（认证管理器），登录时认证使用
     *
     * @param authenticationConfiguration AuthenticationConfiguration
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

}
